/*
 *所有关于materialfactorycost类的业务代码应在此处编写
*可使用repository.调用常用方法，获取EF/Dapper等信息
*如果需要事务请使用repository.DbContextBeginTransaction
*也可使用DBServerProvider.手动获取数据库相关信息
*用户信息、权限、角色等使用UserContext.Current操作
*materialfactorycostService对增、删、改查、导入、导出、审核业务代码扩展参照ServiceFunFilter
*/
using DGZImp.Core.BaseProvider;
using DGZImp.Core.Extensions.AutofacManager;
using ATkg.BizAppProject.DomainModels;
using System.Linq;
using DGZImp.Core.Utilities;
using System.Linq.Expressions;
using DGZImp.Core.Extensions;

using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using ATkg.BizAppProject.IRepositories;
using DGZImp.Core.EFDbContext;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using NetTaste;
using Newtonsoft.Json.Linq;
using MySqlConnector;

namespace ATkg.BizAppProject.Services
{
    public partial class materialfactorycostService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly ImaterialfactorycostRepository _repository;//访问数据库


        public ISqlSugarClient Db = AutofacContainerModule.GetService<ServiceDbContext>()?.SqlSugarClient;
        public IConfiguration _config;
        public HttpClient client = null;
        public static IHttpClientFactory _httpClientFactory { get; set; }

        public AmesSyncService ames = AutofacContainerModule.GetService<AmesSyncService>();
        public ILogger<AmesSyncService> logger { get; set; }

        public Task<object> Syncname_cai()
        {

            Console.WriteLine("我执行了: ");
            //string connectionString = "server=10.16.12.72;user=root;database=caiwu;port=3306;password=fastbee;";
            string connectionString = "Server=10.7.4.214;Port=3306;Database=imr_client;Uid=root;Pwd=12345678;";
            var r = new List<object>();

            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    conn.Open();
                    string sql = "SELECT * FROM `at_device`";

                    MySqlCommand cmd = new MySqlCommand(sql, conn);
                    MySqlDataReader reader = cmd.ExecuteReader();

                    while (reader.Read())
                    {
                        r.Add(new
                        {
                            name = reader["name"],
                            spec = reader["spec"]
                        });
                    }
                    reader.Close();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("错误: " + ex.Message);

                }
            }


            return Task.FromResult<object>(new
            {
                rows = r,
                total = r.Count
            });
        }
        // 定义与 JSON 结构匹配的模型类
        // 定义对应的数据模型类
        public class SteelGradeData
        {
            public List<object> steelgrade_id { get; set; }
            public double batch_todo_qty { get; set; }
            public int id { get; set; }
            public List<object> schedule_blank_id { get; set; }
        }

        public class MyItem
        {
            public List<object> steelgrade_id { get; set; } // 假设 steelgrade_id 是 object 列表
            public double batch_todo_qty { get; set; }
            public int id { get; set; }
            public List<object> schedule_blank_id { get; set; }
        }

        [ActivatorUtilitiesConstructor]
        public materialfactorycostService(
            ImaterialfactorycostRepository dbRepository,
            IHttpContextAccessor httpContextAccessor
            )
        : base(dbRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            _repository = dbRepository;
            //多租户会用到这init代码，其他情况可以不用
            //base.Init(dbRepository);
        }

        static string FormatDate(DateTime date)
        {
            return date.ToString("yyyy-MM-dd HH:mm:ss");
        }

        public async Task<object> GetMaterialProMes(string start_data = "", string end_data = "")
        {
            Console.WriteLine("进来了！！！");
            ames.userName = "duyang@atmcn.com";
            ames.password = "Du123456*";
            //ames.url = "http://10.7.1.9/jsonrpc";
            //ames.db = "prd0803";
            var isSingle = start_data.IsValuable();
            Console.WriteLine(start_data);
            var typeArray = new[] { "final" };

            var qDomain = new List<object> {};

            if (isSingle)
            {
                Console.WriteLine("DDDDDD");
                qDomain.Add(new List<object> { "date_stock_done", ">=", start_data });
                qDomain.Add(new List<object> { "date_stock_done", "<=", end_data });
                //Console.WriteLine(qDomain.ToArrayString);
            }
            //else
            //{
            //    qDomain.Add(new List<object> { "state", "=", "in_production" });
            //}

            var qFields = new List<string> {
                "id",
                "blank_weight"
            };
            var qPage = new
            {
                limit = 100000,
                offset = 0
            };

            var res = await ames.Get_stoke_("mrp.production.report.blank", qDomain, qFields, qPage);
            var r = (JArray)res["result"];
            Console.WriteLine(r.Count);
            Console.WriteLine(res);
            //float total_pro = 0;
            //for(int i = 0; i < r.Count; i++)
            //{
            //    total_pro += (float)r[i]["blank_weight"];
            //}
            //Console.WriteLine(total_pro);
            return new
            {
                rows = r,
                total = res.Count
            };
        }


        public async Task<object> get_db_get_db_eng(string startTime, string endtime)
        {
            Console.WriteLine("进来了！！");
            // 查询数据库中当天最大的code
            // 使用 SqlSugar 的 Queryable 语法
            //string connectionString = "server=localhost;port=3306;database=biz_app;user=root;password=admin;";
            string connectionString = "Server=10.7.4.214;Port=3306;Database=imr_client;Uid=root;Pwd=12345678;";
            var final_data_info = new List<object>();
            //string query = @"
            //SELECT * 
            //FROM at_step 
            //WHERE item1 = @item1 
            //AND dr = @dr";
            ////var updater = new MaterialPlanUpdater1();
            ////updater.UpsertData(plan_data_final);
            //QueryAtStepData(connectionString);
            //QueryJune2025Data(connectionString);

            var result = get_eng(connectionString, startTime, endtime);

            return result;
        }


        public List<object> get_eng(string connect_string, string startTime, string endtime)
        {
            // 数据库连接字符串（根据实际情况修改）
            string connectionString = connect_string;
            Console.WriteLine(startTime);
            Console.WriteLine(endtime);

            // 构建参数化查询语句
            string query = @"
            SELECT 
                (SELECT name FROM at_region WHERE pk = ad.pk_region) AS region_name,
                (SELECT name FROM at_step WHERE pk = ad.pk_step) AS step_name,
                ad.`name`,
                ade.`vriable_value_now`,
                ade.inputtime 
            FROM at_data_energy ade
            LEFT JOIN at_device ad ON ade.pk_device = ad.pk
            WHERE ade.inputtime >= @startTime
              AND ade.inputtime < @endTime
            ORDER BY ad.name, ade.inputtime"
            ;

            try
            {

                var final_data_info_ = new List<object>();
                using (MySqlConnection connection = new MySqlConnection(connectionString))
                {
                    // 创建命令对象
                    using (MySqlCommand command = new MySqlCommand(query, connection))
                    {
                        // 设置参数值
                        command.Parameters.AddWithValue("@startTime", startTime);
                        command.Parameters.AddWithValue("@endTime", endtime);
                        Console.WriteLine(query);

                        // 打开连接
                        connection.Open();

                        // 执行查询
                        using (MySqlDataReader reader = command.ExecuteReader())
                        {
                            // 输出列标题
                            Console.WriteLine($"{"Region",15} {"Step",10} {"Device",20} {"Value",15} {"Time",20}");

                            var i = 0;
                            // 读取数据
                            while (reader.Read())
                            {
                                // 读取各列数据（注意列名与查询结果对应）
                                string region = reader["region_name"].ToString();
                                string step = reader["step_name"].ToString();
                                string device = reader["name"].ToString();
                                string value = reader["vriable_value_now"].ToString();
                                DateTime time = (DateTime)reader["inputtime"];

                                // 格式化输出
                                Console.WriteLine($"{region,15} {step,10} {device,20} {value,15} {time:yyyy-MM-dd HH:mm:ss,20}");
                                var final_data = new Dictionary<string, string>
                                {
                                    { "region_name", reader["region_name"].ToString() }, // 空配置字段
                                    {"step_name",reader["step_name"].ToString() },
                                    { "name", reader["name"].ToString()},          // 空配置字段, // 空配置字段
                                    { "vriable_value_now", reader["vriable_value_now"].ToString() }
                                };
                                i++;
                                var finnn = new List<string>();
                                finnn.Add(reader["region_name"].ToString());
                                finnn.Add(reader["step_name"].ToString());
                                finnn.Add(reader["region_name"].ToString());
                                finnn.Add(reader["region_name"].ToString());

                                final_data_info_.Add(final_data);
                            }
                            Console.WriteLine($"{i} records");
                        }
                    }
                }
                return final_data_info_;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"数据库操作异常: {ex.Message}");
                var r = new List<object>();
                var final_data = new Dictionary<string, object>
                { };
                r.Add(
                    final_data
                    );
                return r;
            }
        }




    }
}
